package com.boe.csb.core.common.pool;

import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.PoolableObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boe.csb.core.common.utils.PropertyUtils;

public class FtpClientFactory implements PoolableObjectFactory<FTPClient> {
	
	private static final Logger logger = LoggerFactory.getLogger(FtpClientFactory.class);
	
	private static final String userName;
	
	private static final String pwd;
	
	private static final String ip;
	
	private static final int port;
	
	private static int defaultFileType = FTP.BINARY_FILE_TYPE;
			
	static{
		userName = PropertyUtils.getProperty("ftp.userName");
		pwd = PropertyUtils.getProperty("ftp.pwd");
		ip = PropertyUtils.getProperty("ftp.ip");
		port = PropertyUtils.getIntProperty("ftp.port");
	}
	
	@Override
	public void activateObject(FTPClient arg0) throws Exception {
		
	}

	@Override
	public void destroyObject(FTPClient ftpClient) throws Exception {
		try{
			if(ftpClient != null && ftpClient.isConnected()){
				ftpClient.logout();
			}
		}catch(IOException ioe){
			logger.error("", ioe);
		}finally{
			try{
				ftpClient.disconnect();
			}catch(IOException ioe){
				logger.error("", ioe);
			}
		}
	}

	@Override
	public FTPClient makeObject() throws Exception {
		FTPClient ftpClient = new FTPClient();
		try{
			ftpClient.connect(ip, port);
			int replyCode = ftpClient.getReplyCode();
			if(!FTPReply.isPositiveCompletion(replyCode)){
				ftpClient.disconnect();
				logger.error("FTPServer refused connection.");
				return null;
			}
			
			boolean result = ftpClient.login(userName, pwd);
			if(!result){
				logger.error("ftp client login failed,userName:{}, pwd:{}.", userName, pwd);
				return null;
			}
			
			ftpClient.setFileType(defaultFileType);
			ftpClient.enterLocalPassiveMode();//设置为被动模式
			
		}catch(Exception e){
			logger.error("connect ftp error:", e);
			return null;
		}
		
		return ftpClient;
		
	}

	@Override
	public void passivateObject(FTPClient arg0) throws Exception {
		
	}

	@Override
	public boolean validateObject(FTPClient ftpClient) {
		try{
			return ftpClient.sendNoOp();
		}catch(IOException ioe){
			logger.debug("this ftpclient has already closed!");
			return false;
		}
	}

}
